package 有效的括号;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Solution {
    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.isValid("(){}}{"));
    }
    public boolean isValid(String s) {
        Map<Character,Integer> map = new HashMap<Character,Integer>(){{
            put('(',1);
            put(')',2);
            put('[',3);
            put(']',4);
            put('{',5);
            put('}',6);
        }};
        int length = s.length();
        if(length % 2 != 0){
            return false;
        }

        char[] chars = s.toCharArray();
        List<Character> list = new ArrayList<>(length / 2);

        char aChar = chars[0];
        list.add(aChar);
        int index = 1;
        while(index < length){
            char tempChar = chars[index];
            if(list.size() == 0){
                list.add(tempChar);
            }
            else if(list.get(list.size()-1) != tempChar && map.get(tempChar) - map.get(list.get(list.size()-1)) == 1){
                list.remove(list.size()-1);
            }
            else {
                list.add(tempChar);
            }
            index++;
        }

        if(list.size() != 0){
            return false;
        }

        return true;
    }
}
